<?php
namespace Leaps\Cache\Adapter;

use Leaps\Database\Connection;
use Leaps\Encryption\Encrypter;
use Leaps\Cache\AdapterInterface;

class Database implements AdapterInterface {

	/**
	 * 数据库连接实例
	 *
	 * @var \Leaps\Database\Connection
	 */
	protected $connection;

	/**
	 * 加密实例
	 *
	 * @param  \Leaps\Encrypter
	 */
	protected $encrypter;

	/**
	 * 缓存表
	 *
	 * @var string
	 */
	protected $table;

	/**
	 * Create a new database store.
	 *
	 * @param  \Leaps\Database\Connection  $connection
	 * @param  \Leaps\Encrypter  $encrypter
	 * @param  string  $table
	 * @param  string  $prefix
	 * @return void
	 */
	public function __construct(Connection $connection, Encrypter $encrypter, $table, $prefix = '')
	{
		$this->table = $table;
		$this->prefix = $prefix;
		$this->encrypter = $encrypter;
		$this->connection = $connection;
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::get()
	 */
	public function get($key)
	{
		$prefixed = $this->$key;
		$cache = $this->table()->where('key', $prefixed)->first();
		if ( ! is_null($cache))
		{
			if (is_array($cache)) $cache = (object) $cache;
			if (time() >= $cache->expiration)
			{
				return $this->forget($key);
			}
			return $this->encrypter->decrypt($cache->value);
		}
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::set()
	 */
	public function set($key, $value, $minutes)
	{
		$key = $this->prefix.$key;
		$value = $this->encrypter->encrypt($value);
		$expiration = $this->getTime() + ($minutes * 60);
		try
		{
			$this->table()->insert(compact('key', 'value', 'expiration'));
		}
		catch (\Exception $e)
		{
			$this->table()->where('key', $key)->update(compact('value', 'expiration'));
		}
	}

	/**
	 * 获得当前系统时间。
	 *
	 * @return int
	 */
	protected function getTime()
	{
		return time();
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::forever()
	 */
	public function forever($key, $value)
	{
		return $this->set($key, $value, 5256000);
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::delete()
	 */
	public function delete($key)
	{
		$this->table()->where('key', $this->prefix.$key)->delete();
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::flush()
	 */
	public function flush()
	{
		$this->table()->delete();
	}

	/**
	 * 得到一个查询生成器的缓存表。
	 *
	 * @return \Leaps\Database\Query\Builder
	 */
	protected function table()
	{
		return $this->connection->table($this->table);
	}

	/**
	 * 得到底层数据库连接。
	 *
	 * @return \Leaps\Database\Connection
	 */
	public function getConnection()
	{
		return $this->connection;
	}

	/**
	 * 获取加密实例
	 *
	 * @return \Leaps\Encrypter
	 */
	public function getEncrypter()
	{
		return $this->encrypter;
	}
}